﻿using System;
using System.Linq;
using UnityEngine;

namespace Core.Extension.ObservableValue
{
    /// 持久化存储，可观察的值
    public class ObservablePlayerPrefsFloat
    {
        private Action<float> _onValueChanged;
        private int _value;
        private readonly string _key;
        private readonly float _defaultValue;

        public float Value
        {
            get => PlayerPrefs.GetFloat(_key, _defaultValue);
            set
            {
                if (value.Equals(Value)) return;
                PlayerPrefs.SetFloat(_key, value);
                PlayerPrefs.Save();
                _onValueChanged?.Invoke(value);
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="key">持久化存储时的key</param>
        /// <param name="defaultValue">使用的默认值</param>
        public ObservablePlayerPrefsFloat(string key, float defaultValue)
        {
            _key = key;
            _defaultValue = defaultValue;
        }

        /// <summary>
        /// 添加监听
        /// </summary>
        /// <param name="action">在Value发生改变时触发</param>
        /// <param name="bindObj">监听所绑定的对象，当对象Destroy时，监听自动移除</param>
        public void AddListener(Action<float> action, GameObject bindObj = null)
        {
            if (_onValueChanged == null || !_onValueChanged.GetInvocationList().Contains(action))
            {
                _onValueChanged += action;
            }

            //绑定自动销毁功能
            if (bindObj != null)   bindObj.OnDestroy(delegate { RemoveListener(action); });
        }

        /// <summary>
        /// 移除某个监听委托
        /// </summary>
        /// <param name="action">在Value发生改变时触发</param>
        public void RemoveListener(Action<float> action)
        {
            if (_onValueChanged != null)
            {
                _onValueChanged -= action;
            }
        }

        /// <summary>
        /// 移除所有监听
        /// </summary>
        public void RemoveAllListeners()
        {
            _onValueChanged = null;
        }
    }
}